<script setup>
import { ref } from 'vue'
import { userService_updateAvatar } from '@/apis/user'
import { ElMessage } from 'element-plus'
import { useUserInfo } from '@/stores/index'
let title = ref('更换头像')
let imageUrl = ref('')
let avatar = ref('')
let visiable = ref(true)
let canUpload = ref(false)
let uploadRef = ref(null)
let useStore = useUserInfo()
const { getUserInfo } = useStore
const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  visiable.value = false
  // 将图片转换为base64
  const reader = new FileReader()
  // 调用readAsDataUrl转换为base64
  reader.readAsDataURL(uploadFile.raw)
  // reader读取完成，赋值到avatar变量中
  reader.onload = () => {
    avatar.value = reader.result
    console.log(avatar.value)
    // 修改上传按钮状态
    canUpload.value = true
  }
}

const uploadAvatar = async () => {
  await userService_updateAvatar(avatar.value)
  ElMessage({
    type: 'success',
    message: '上传成功'
  })
  // 同步到pinia，重新请求一下个人信息接口
  getUserInfo()
}

// 选择图片，实现上传功能
const selectImage = () => {
  console.log(uploadRef.value)
}
</script>

<template>
  <CardPage :title="title">
    <template #extra>
      <el-upload
        ref="uploadRef"
        class="avatar-uploader"
        action="https://fe-bigevent-web.itheima.net/da3dd87e-7eb4-42a4-a9c4-ecf96d44cf94"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <!-- <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon> -->
        <div class="avatar-uploader" v-show="visiable">请选择头像</div>
      </el-upload>

      <div class="btns">
        <el-button type="primary" @click="selectImage">
          <el-icon>
            <Plus></Plus>
          </el-icon>
          选择图片
        </el-button>
        <el-button
          class="ml-3"
          type="success"
          @click="uploadAvatar"
          :disabled="!canUpload"
        >
          <el-icon>
            <Upload></Upload>
          </el-icon>
          上传头像
        </el-button>
      </div>
    </template>
  </CardPage>
</template>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 180px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader {
  line-height: 178px;
  height: 178px;
  width: 178px;
  font-size: 16px;
  color: #8c939d;
  text-align: center;
}

.btns {
  margin-top: 20px;
}

.el-icon {
  margin-right: 6px;
}
</style>
